package com.bluegalaxy.nhb.snservice.core.util;

import com.sun.mail.smtp.SMTPTransport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;

/**
 * Created by ZhangMJ on 2016/7/6.
 */
public class MailUtil {
    private static Log log = LogFactory.getLog(MailUtil.class);
    final static String mailhost = "mail.qq.com";
    final static String mailFrom = "test@qq.com";
    final static String mailUsername = "test";
    final static String mailPassword = "testqq";


    /**
     * 发送邮件工具，内容以html文档解析 ，换车换为“<br/>”
     *
     * @param to          收件人
     * @param cc          抄送
     * @param bcc         密送
     * @param subject     主题
     * @param message     邮件正文
     * @param csvFileList 附件
     * @throws MessagingException
     * @throws IOException
     */
    public static void postMailHtml(String to, String cc, String bcc, String subject, String message, ArrayList<File> csvFileList) throws MessagingException, IOException {
        postMailUtilDefault(to, cc, bcc, subject, message, csvFileList, true);
    }

    /**
     * 发送邮件工具类，有默认的用户名密码
     *
     * @param to
     * @param cc
     * @param bcc
     * @param subject
     * @param message
     * @param csvFileList
     * @param isHtml      是否以html形式翻译正文
     * @throws MessagingException
     * @throws IOException
     */
    public static void postMailUtilDefault(String to, String cc, String bcc, String subject, String message, ArrayList<File> csvFileList, boolean isHtml) throws MessagingException, IOException {
        postMailUtil(to, cc, bcc, subject, message, mailFrom, csvFileList, mailUsername, mailPassword, isHtml);
    }

    /**
     * 发邮件工具类，正文不翻译成html
     *
     * @param to
     * @param cc
     * @param bcc
     * @param subject
     * @param message
     * @param csvFileList
     * @throws MessagingException
     * @throws IOException
     */
    public static void postMailUtilNoHtml(String to, String cc, String bcc, String subject, String message, ArrayList<File> csvFileList) throws MessagingException, IOException {
        postMailUtilDefault(to, cc, bcc, subject, message, csvFileList, false);
    }

    /**
     * 发送邮件工具类
     *
     * @param to          收件人
     * @param cc          抄送
     * @param bcc         待定
     * @param subject     主题
     * @param message     邮件正文
     * @param from        发件人邮箱
     * @param csvFileList 附件
     * @param username    用户名
     * @param password    密码
     * @param isHtml      是否是以html格式解析
     * @throws MessagingException
     * @throws IOException
     */
    public static void postMailUtil(String to, String cc, String bcc, String subject, String message, String from, ArrayList<File> csvFileList, String username, String password, boolean isHtml) throws MessagingException, IOException {
        boolean debug = false;
        boolean auth = true;
        Properties props = System.getProperties();
        if (mailhost != null)
            props.put("mail.smtp.host", mailhost);
        if (auth)
            props.put("mail.smtp.auth", "true");
        // Get a Session object
        Session session = Session.getInstance(props, null);
        if (debug)
            session.setDebug(true);
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();
        /**支持给多人发送邮件，收件人邮件地址以空格分隔 by wangsen 2014-2-24*/
        InternetAddress[] toAddrs = InternetAddress.parse(to, false);
        msg.setRecipients(Message.RecipientType.TO, toAddrs);

        if (cc != null)
            msg.setRecipients(Message.RecipientType.CC,
                    InternetAddress.parse(cc, false));
        if (bcc != null)
            msg.setRecipients(Message.RecipientType.BCC,
                    InternetAddress.parse(bcc, false));
        msg.setSubject(subject);

        MimeBodyPart mbp1 = new MimeBodyPart();
        if (isHtml) {
            mbp1.setContent(message, "text/html;charset = UTF-8");
        } else {
            mbp1.setText(message);
        }
        MimeMultipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        if (csvFileList != null && csvFileList.size() > 0) {
            for (int i = 0; i < csvFileList.size(); i++) {
                File file = (File) csvFileList.get(i);
                if (file != null) {
                    MimeBodyPart mbp2 = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(file);
                    mbp2.setDataHandler(new DataHandler(fds));
                    mbp2.setFileName(MimeUtility.encodeWord(fds.getName(), "UTF-8", null));
                    mp.addBodyPart(mbp2);
                }


            }
        }
        msg.setContent(mp);

        String mailer = "smtpsend";
        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());
        SMTPTransport t = (SMTPTransport) session.getTransport("smtp");
        try {
            if (auth)
                t.connect(mailhost, username, password);
            else
                t.connect();
            try {
                t.sendMessage(msg, msg.getAllRecipients());
            } catch (Exception se) {
                log.debug("邮件发送失败!  to:" + to + "  cc:" + cc + "   bcc:" + bcc);
            }

        } finally {

            t.close();
        }

    }
}
